package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"fmt"
	"io/ioutil"
	"time"
)
// 公钥内容加密
func rsaPubEncrypt(filePath_name string, text []byte) []byte {
	info, err := ioutil.ReadFile(filePath_name)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	block, rest := pem.Decode(info)
	fmt.Println("block1=", base64.StdEncoding.EncodeToString(block.Bytes))
	fmt.Println("rest=", rest)
	// 3.解码得到公钥
	derText := block.Bytes
	publicKey,err:=x509.ParsePKCS1PublicKey(derText)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	fmt.Println("publicKey=", publicKey)
	cipherData,err:=rsa.EncryptPKCS1v15(rand.Reader,publicKey, text)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	fmt.Println("加密成功！")
	return cipherData
}

// 私钥解密
// 内容解密
func rsaPrivDecrypt(filePath_name string, text []byte) []byte {
	info, err := ioutil.ReadFile(filePath_name)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	block, rest := pem.Decode(info)

	fmt.Println("rest=", rest)
	// 3.解码得到s钥
	derText := block.Bytes
	privlicKey,err:=x509.ParsePKCS1PrivateKey(derText)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	//fmt.Println("publicKey=", privlicKey)
	decryptcontent,err:=rsa.DecryptPKCS1v15(rand.Reader,privlicKey,text)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	fmt.Println("内容解密成功！")
	return decryptcontent
}

func main() {
	src:=rsaPubEncrypt(`./publicRsaKey.pem`, []byte("你好，王彦超。本轮测试内容为：知道了，下次一定。"))
	fmt.Println("加密后内容为：",src)
	fmt.Println("开始解密。")
	time.Sleep(time.Second*10)
	text:=rsaPrivDecrypt(`./privateRsaKey.pem`,src)
	fmt.Println("解密成功！")
	fmt.Println("解密后内容为：",string(text))
}
